package com.dexilaonian.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.dexilaonian.R;
import com.dexilaonian.bean.PspecBean2;
import com.dexilaonian.model.AddressPickTask;
import com.dexilaonian.ui.BaseActivity;
import com.dexilaonian.utils.Constant;
import com.dexilaonian.utils.Logutil;
import com.dexilaonian.utils.Okhttp;
import com.dexilaonian.utils.PublicUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.addapp.pickers.entity.City;
import cn.addapp.pickers.entity.County;
import cn.addapp.pickers.entity.Province;
import cn.addapp.pickers.picker.NumberPicker;
import okhttp3.Call;

public class NewAddressActivity extends BaseActivity {
    @Bind(R.id.back)
    ImageView back;
    @Bind(R.id.base_title_service)
    TextView baseTitleService;
    @Bind(R.id.et_address_name)
    EditText etAddressName;
    @Bind(R.id.et_address_phone)
    EditText etAddressPhone;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.rl_address)
    RelativeLayout rlAddress;
    @Bind(R.id.et_detail_address)
    EditText etDetailAddress;
    @Bind(R.id.address_moren)
    ImageView addressMoren;
    @Bind(R.id.btn_address_save)
    Button btnAddressSave;
    @Bind(R.id.et_address_postcode)
    EditText etAddressPostcode;
    private String provinceStr;
    private String cityStr;
    private String countyStr;
    private String myprovice;
    private String mycity;
    private String mycounty;
    private boolean mPositon = true;
    private int postion = 0;
    private String newaddress_url;
    private String address_id;
    private String pspec;
    private int productId;
    private int quantity;
    private ArrayList<PspecBean2> serInfo;
    private String confirms;
    private com.alibaba.fastjson.JSONObject json;
    private JSONArray jsonArray2 = new JSONArray();
    @Override
    public int getLayoutID() {
        return R.layout.activity_new_address;
    }

    @Override
    public void initView() {

    }

    @Override
    protected void initData() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
        baseTitleService.setText("新建收货地址");
        Intent intent = getIntent();
        if (intent != null) {
            Bundle extras = intent.getExtras();
            if (extras != null) {
                String num = extras.getString("NUM");
                confirms = extras.getString("CONFIRMS");

                if (num.equals("MM")) {
                    if (confirms.equals("CONFIRMS")) {
                        json = new com.alibaba.fastjson.JSONObject();
                        pspec = extras.getString("pspec");
                        productId = extras.getInt("productId");
                        quantity = extras.getInt("quantity");
                        json.put("pspec", pspec);
                        json.put("quantity", quantity);
                        json.put("productId", productId);
                        jsonArray2.add(json);
                    } else {
                        serInfo = (ArrayList<PspecBean2>) intent.getSerializableExtra("PSPS");
                    }
                } else {
                    if ("CONFIRMS".equals(confirms)) {
                        json = new com.alibaba.fastjson.JSONObject();
                        pspec = extras.getString("pspec");
                        productId = extras.getInt("productId");
                        quantity = extras.getInt("quantity");
                        json.put("pspec", pspec);
                        json.put("quantity", quantity);
                        json.put("productId", productId);
                        jsonArray2.add(json);
                    } else {
                        serInfo = (ArrayList<PspecBean2>) intent.getSerializableExtra("PSPS");
                    }
                    address_id = extras.getString("addressid");
                    String mangerName = extras.getString("mangerName");
                    String receiverPhone = extras.getString("receiverPhone");
                    String receiverProvince = extras.getString("receiverProvince");
                    String receiverCity = extras.getString("receiverCity");
                    String receiverDistrict = extras.getString("receiverDistrict");
                    String receiverZIP = extras.getString("receiverZIP");
                    String receiverAddress = extras.getString("receiverAddress");
                    String isDefault = extras.getString("isDefault");
                    if (!TextUtils.isEmpty(mangerName)) {
                        etAddressName.setText(mangerName);
                    }
                    if (!TextUtils.isEmpty(receiverPhone)) {
                        etAddressPhone.setText(receiverPhone);
                    }

                    if (!TextUtils.isEmpty(receiverProvince) || !TextUtils.isEmpty(receiverCity) || !TextUtils.isEmpty(receiverDistrict)) {
                        tvAddress.setText(receiverProvince + " " + receiverCity + " " + receiverDistrict);
                    }

                    if (!TextUtils.isEmpty(receiverZIP)) {
                        etAddressPostcode.setText(receiverZIP);
                    }
                    if (!TextUtils.isEmpty(receiverAddress)) {
                        etDetailAddress.setText(receiverAddress);
                    }
                    if (isDefault.equals("true")) {
                        addressMoren.setImageDrawable(getDrawable(R.drawable.queren));
                    } else {
                        addressMoren.setImageDrawable(getDrawable(R.drawable.weiqueren));
                    }
                    postion = 1;
                }
            }
        }
    }

    @OnClick({R.id.back, R.id.rl_address, R.id.address_moren, R.id.btn_address_save})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.back:
                finish();
                break;
            case R.id.rl_address:
                wheel();
                break;
            case R.id.address_moren:
                if (mPositon == true) {
                    mPositon = false;
                    addressMoren.setImageDrawable(getDrawable(R.drawable.weiqueren));
                } else {
                    mPositon = true;
                    addressMoren.setImageDrawable(getDrawable(R.drawable.queren));
                }
                break;
            case R.id.btn_address_save:
                String addressName = etAddressName.getText().toString().trim();
                String addressphone = etAddressPhone.getText().toString().trim();
                String address = tvAddress.getText().toString().trim();
                String addessDetail = etDetailAddress.getText().toString().trim();
                String addressPostcode = etAddressPostcode.getText().toString().trim();
                if (TextUtils.isEmpty(addressName)) {
                    showToast("请填写收货人姓名");
                    return;
                }
                if (TextUtils.isEmpty(addressphone)) {
                    showToast("请填写收货人电话");
                    return;
                }
                if (addressphone.length() != 11 || !PublicUtil.isMobileNO(addressphone)) {
                    Toast.makeText(this, "手机号码格式不正确", Toast.LENGTH_SHORT).show();
                    return;
                }

                if (TextUtils.isEmpty(addressPostcode)) {
                    showToast("请填写邮政编号");
                    return;
                }
                if (TextUtils.isEmpty(address)) {
                    showToast("请选择地址");
                    return;
                } else {
                    String[] split = address.split(" ");
                    myprovice = split[0];
                    mycity = split[1];
                    mycounty = split[2];
                }

                if (TextUtils.isEmpty(addessDetail)) {
                    showToast("请填写详细地址");
                    return;
                }
                initSaveAdress(addressName, addressphone, myprovice, mycity, mycounty, addressPostcode, addessDetail, mPositon);
                break;
        }
    }

    private void initSaveAdress(String addressName, String addressphone, String myprovice, String mycity, String mycounty, String addresspostcode, String addessDetail, boolean mPositon) {
        showProgressBar(true);
        Map<String, String> addressMap = new HashMap<>();
        if (postion == 1) {
            newaddress_url = Constant.base_url + "/shipping/edit.do";
            if (!TextUtils.isEmpty(address_id)) {
                addressMap.put("addressId", address_id);
            }
        } else {
            newaddress_url = Constant.base_url + "/shipping/save_address.do";
        }
        addressMap.put("receiverAddress", addessDetail);//收货详细地址
        addressMap.put("receiverDistrict", mycounty);//收货所在区县
        addressMap.put("receiverCity", mycity);//收货所在市
        addressMap.put("receiverName", addressName);//收货人姓名
        addressMap.put("receiverPhone", addressphone);//收货人电话
        addressMap.put("receiverProvince", myprovice);//收货所在省
        addressMap.put("receiverZIP", addresspostcode);//邮编
        addressMap.put("isDefault", mPositon + "");// 是否默认

        Okhttp.postString(true, newaddress_url, addressMap, new Okhttp.CallBac() {
            @Override
            public void onError(Call call, Exception e, String state, int id) {
                showProgressBar(false);
                showToast(state);
            }

            @Override
            public void onResponse(String response, int id) {
                showProgressBar(false);
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    int status = Integer.parseInt(jsonObject.optString("status"));
                    if (status == 16 || status == 34) {
                        startActivity(new Intent(NewAddressActivity.this, LoginActivity.class));
                        finish();
                    }
                    if (status == 39) {
                        showToast("该地址不存在");
                        return;
                    }
                    if (status == 0) {
                        Log.e("TTTTTTTTTTNUN", confirms);
                        Intent intent = new Intent(NewAddressActivity.this, MangerAddressActivity.class);
                        if (confirms.equals("CONFIRMS")) {
                            intent.putExtra("productId", productId);
                            intent.putExtra("quantity", quantity);
                            intent.putExtra("pspec", pspec);
                            intent.putExtra("CONFIRMS", "CONFIRMS");
                        } else {
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("PSPS",serInfo);
                            intent.putExtras(bundle);
                            intent.putExtra("CONFIRMS", "CONFIRMS1");
                        }
                        startActivity(intent);
                        finish();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onNoNetwork(String state) {
                showProgressBar(false);
                showToast(state);
            }
        });
    }

    /**
     * 弹出选择器
     */
    private void wheel() {
        AddressPickTask task = new AddressPickTask(this);
        task.setHideProvince(false);
        task.setHideCounty(false);

        task.setCallback(new AddressPickTask.Callback() {


            @Override
            public void onAddressInitFailed() {
                showToast("数据初始化失败");
            }

            @Override
            public void onAddressPicked(Province province, City city, County county) {
                provinceStr = province.getAreaName();
                cityStr = city.getAreaName();
                countyStr = county.getAreaName();
                tvAddress.setText(provinceStr + " " + cityStr + " " + countyStr);
            }
        });
        task.execute("广东 ", "深圳 ", "福田");
    }
}
